/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.subgoods.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.mapper.AccountMapper;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.centerrecord.service.CenterRecordService;
import com.jeeplus.modules.freezingassets.entity.FreezingAssets;
import com.jeeplus.modules.freezingassets.mapper.FreezingAssetsMapper;
import com.jeeplus.modules.freezingassets.service.FreezingAssetsService;
import com.jeeplus.modules.integraldetail.entity.IntegralDetail;
import com.jeeplus.modules.integraldetail.service.IntegralDetailService;
import com.jeeplus.modules.investmentrecord.entity.InvestmentRecord;
import com.jeeplus.modules.investmentrecord.mapper.InvestmentRecordMapper;
import com.jeeplus.modules.investmentrecord.service.InvestmentRecordService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.positionassets.entity.PositionAssets;
import com.jeeplus.modules.positionassets.mapper.PositionAssetsMapper;
import com.jeeplus.modules.positionassets.service.PositionAssetsService;
import com.jeeplus.modules.purchaseorder.entity.PurchaseOrder;
import com.jeeplus.modules.purchaseorder.mapper.PurchaseOrderMapper;
import com.jeeplus.modules.purchaseorder.service.PurchaseOrderService;
import com.jeeplus.modules.saleorder.entity.SaleOrder;
import com.jeeplus.modules.saleorder.mapper.SaleOrderMapper;
import com.jeeplus.modules.saleorder.service.SaleOrderService;
import com.jeeplus.modules.subrecord.entity.SubRecord;
import com.jeeplus.modules.subrecord.service.SubRecordService;
import com.jeeplus.modules.takegoods.entity.TakeGoods;
import com.jeeplus.modules.takegoods.service.TakeGoodsService;
import com.jeeplus.modules.turntobalance.entity.TurnToBalance;
import com.jeeplus.modules.turntobalance.service.TurnToBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.subgoods.entity.SubGoods;
import com.jeeplus.modules.subgoods.mapper.SubGoodsMapper;
import redis.clients.jedis.Jedis;

/**
 * 认购商品Service
 * @author w
 * @version 2021-03-25
 */
@Service
@Transactional(readOnly = true)
public class SubGoodsService extends CrudService<SubGoodsMapper, SubGoods> {
	@Autowired
	private TakeGoodsService takeGoodsService;
	@Autowired
	private PositionAssetsService positionAssetsService;
	@Autowired
	private FreezingAssetsService freezingAssetsService;
	@Autowired
	private FreezingAssetsMapper freezingAssetsMapper;
	@Autowired
	private MemberService memberService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private InvestmentRecordService investmentRecordService;
	@Autowired
	private InvestmentRecordMapper investmentRecordMapper;
	@Autowired
	private PurchaseOrderService purchaseOrderService;
	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private IntegralDetailService integralDetailService;
	@Autowired
	private PurchaseOrderMapper purchaseOrderMapper;
	@Autowired
	private SaleOrderMapper saleOrderMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private PositionAssetsMapper positionAssetsMapper;
	@Autowired
	private SubRecordService subRecordService;
	@Autowired
	private CenterRecordService centerRecordService;
	@Autowired
	private TurnToBalanceService turnToBalanceService;

	public SubGoods get(String id) {
		return super.get(id);
	}
	
	public List<SubGoods> findList(SubGoods subGoods) {
		return super.findList(subGoods);
	}
	
	public Page<SubGoods> findPage(Page<SubGoods> page, SubGoods subGoods) {
		return super.findPage(page, subGoods);
	}
	
	@Transactional(readOnly = false)
	public void save(SubGoods subGoods) {
		if (subGoods.getIsNewRecord()){
			//插入提货商品
			TakeGoods takeGoods = new TakeGoods();
			takeGoods.setGoodsName(subGoods.getGoodsName());
			takeGoods.setGoodsPic(subGoods.getGoodsPic());
			takeGoods.setGoodsImgs(subGoods.getGoodsImgs());
			takeGoods.setGoodsPrice(subGoods.getPrice());
			takeGoodsService.save(takeGoods);
			subGoods.setIsUnloading("0");
			subGoods.setStock(0);
		}
		super.save(subGoods);
	}
	
	@Transactional(readOnly = false)
	public void delete(SubGoods subGoods) {
		//改逻辑删除
		mapper.deleteByLogic(subGoods);
	}

	public List<SubGoods> findGoods(SubGoods subGoods) {
		return mapper.findGoods(subGoods);
	}

	/**
	 * 认购商品下架
	 * @param subGoods
	 */
	@Transactional(readOnly = false)
	public void unloading(SubGoods subGoods) {
		handleInvestment(subGoods);
//		subGoods.setIsUnloading("1");
//		save(subGoods);
	}



	/**
	 * 资产下架及复购
	 * @param subGoods
	 */
	@Transactional(readOnly = false)
	public void handleInvestment(SubGoods subGoods) {
		// 撤销所有相关商品的买卖订单
		PurchaseOrder purchaseOrder = new PurchaseOrder();
		purchaseOrder.setSubGoods(subGoods);
		List<PurchaseOrder> purchaseOrders = purchaseOrderService.findList(purchaseOrder);
		if (purchaseOrders.size()>0){
			for (PurchaseOrder order : purchaseOrders) {
				order.setIsRevoke("1");
				order.preUpdate();
				purchaseOrderMapper.update(order);
			}
		}
		SaleOrder saleOrder = new SaleOrder();
		saleOrder.setSubGoods(subGoods);
		List<SaleOrder> saleOrders = saleOrderService.findList(saleOrder);
		if (saleOrders.size()>0){
			for (SaleOrder order : saleOrders) {
				order.setIsRevoke("1");
				order.preUpdate();
				saleOrderMapper.update(order);
			}
		}
		//查询相关持仓资产
		PositionAssets positionAssets = new PositionAssets();
		positionAssets.setSubGoods(subGoods);
		positionAssets.setIsApply("0");
		List<PositionAssets> positionAssetsList = positionAssetsService.findList(positionAssets);
		if (positionAssetsList.size()>0){
			for (PositionAssets assets : positionAssetsList) {
				//查询相关锁仓资产
				FreezingAssets freezingAssets = freezingAssetsService.findByMember(assets.getMember(),subGoods);
				Double freezingTotal = 0.0;
				if (freezingAssets != null){
					freezingTotal = freezingAssets.getNowTotal();
				}
				//计算总价值
				Double total = assets.getNowTotal()+freezingTotal;
				//查询用户
				Member member = memberService.get(assets.getMember().getId());
				if (member != null){
					//统计15318988288下用户的复投金额
//					querySum(member,total);


					Account account = accountService.get(member.getAccount().getId());
					if (account != null){
						//记录下架转余额记录
						//下架轮数
						Integer downRound = subGoods.getRoundsNumber();
						//下架转余额
						Double downMoney = 0.0;
						//30%到积分
						account.setIntegral(account.getIntegral()+(total*0.3));
						//记录积分明细
						IntegralDetail integralDetail = new IntegralDetail();
						integralDetail.setMember(member);
						integralDetail.setIntegral(total*0.3);
						integralDetail.setIntegralType("0");
						integralDetailService.save(integralDetail);
						//剩余70%
						//查询新一轮商品单价
						Double newPrice = findNewRoundsPrice(subGoods.getRoundsNumber()+3);
						//不足一套   返还到余额
						if (total*0.7<newPrice){
							account.setYue(account.getYue()+total*0.7);
							downMoney += total*0.7;
						}else {
							//计算够买几套新一轮商品
							BigDecimal unloadingTotal = BigDecimal.valueOf(total*0.7).divide(BigDecimal.valueOf(newPrice),0,BigDecimal.ROUND_DOWN);
							//不足5套
							if (unloadingTotal.doubleValue() >= 1 && unloadingTotal.doubleValue() <5){
								//剩下不足一套的钱
								Double balance = (total*0.7)-(unloadingTotal.doubleValue()*newPrice);
								if (balance > 0){
									account.setYue(account.getYue()+balance);
									downMoney += balance;
								}
								//扣除零的 其他放入锁仓  先进入待复投记录，等对应轮数的商品开始认购，再记录
								InvestmentRecord investmentRecord = new InvestmentRecord();
								investmentRecord.setId(IdGen.uuid());
								investmentRecord.setFreezingAmount(unloadingTotal.intValue());
								investmentRecord.setPrice(newPrice);
								investmentRecord.setPositionAmount(0);
								investmentRecord.setMember(member);
								investmentRecord.setRoundingNumber(subGoods.getRoundsNumber()+3);
								investmentRecord.setSubAmount(0);
								investmentRecord.preInsert();
								investmentRecordMapper.insert(investmentRecord);
							}else if (unloadingTotal.doubleValue() >= 5){
								//下架资产够五套
								BigDecimal newQuantity = unloadingTotal.divide(BigDecimal.valueOf(5),0,BigDecimal.ROUND_DOWN);
								InvestmentRecord investmentRecord = new InvestmentRecord();
								investmentRecord.setId(IdGen.uuid());
								investmentRecord.setRoundingNumber(subGoods.getRoundsNumber()+3);
								investmentRecord.setMember(member);
								investmentRecord.setPrice(newPrice);
								investmentRecord.setSubAmount(newQuantity.multiply(BigDecimal.valueOf(5)).intValue());
								//扣除待认购剩下的
								BigDecimal balance = BigDecimal.valueOf(total*0.7).subtract(newQuantity.multiply(BigDecimal.valueOf(5).multiply(BigDecimal.valueOf(newPrice))));
								//计算剩下的资产是否够一套
								BigDecimal ba = balance.divide(BigDecimal.valueOf(newPrice),0,BigDecimal.ROUND_DOWN);
								if (ba.compareTo(BigDecimal.valueOf(1)) == -1){
									//不够一套的   进入余额
									account.setYue(account.getYue()+balance.doubleValue());
									downMoney += balance.doubleValue();
									investmentRecord.setFreezingAmount(ba.intValue());
								}
								else {
									//整数的进入锁仓  剩下的进入余额
									investmentRecord.setFreezingAmount(ba.intValue());
									BigDecimal lastBalance = balance.subtract(BigDecimal.valueOf(newPrice).multiply(ba));
									account.setYue(lastBalance.doubleValue()+account.getYue());
									downMoney += lastBalance.doubleValue();
								}
								investmentRecord.preInsert();
								investmentRecordMapper.insert(investmentRecord);
							}
						}
						account.preUpdate();
						accountMapper.update(account);
//						//下架
//						subGoods.setIsUnloading("1");
//						save(subGoods);
						//记录转余额
						TurnToBalance turnToBalance = new TurnToBalance();
						turnToBalance.setMember(member);
						turnToBalance.setDownRounds(downRound);
						turnToBalance.setUpRounds(downRound + 3);
						turnToBalance.setDownMoney(downMoney);
						turnToBalanceService.save(turnToBalance);
					}
				}
				freezingAssetsService.delete(freezingAssets);
				positionAssetsService.delete(assets);
			}
		}
		//只有冻结的资产
		FreezingAssets freezingAssets = new FreezingAssets();
		freezingAssets.setSubGoods(subGoods);
		freezingAssets.setIsApply("0");
		List<FreezingAssets> freezingAssetsList = freezingAssetsService.findList(freezingAssets);
		if (freezingAssetsList.size()>0){
			for (FreezingAssets assets : freezingAssetsList) {
				//计算总价值
				Double total = assets.getNowTotal();
				//查询用户
				Member member = memberService.get(assets.getMember().getId());
				if (member != null){
					//统计15318988288下用户的复投金额
//					querySum(member,total);


					Account account = accountService.get(member.getAccount().getId());
					if (account != null){
						//记录下架转余额记录
						//下架轮数
						Integer downRound = subGoods.getRoundsNumber();
						//下架转余额
						Double downMoney = 0.0;
						//30%到积分
						account.setIntegral(account.getIntegral()+(total*0.3));
						//记录积分明细
						IntegralDetail integralDetail = new IntegralDetail();
						integralDetail.setMember(member);
						integralDetail.setIntegral(total*0.3);
						integralDetail.setIntegralType("0");
						integralDetailService.save(integralDetail);
						//剩余70%
						//查询新一轮商品单价
						Double newPrice = findNewRoundsPrice(subGoods.getRoundsNumber()+3);
						//不足一套   返还到余额
						if (total*0.7<newPrice){
							account.setYue(account.getYue()+total*0.7);
							downMoney += total*0.7;
						}else {
							//计算够买几套新一轮商品
							BigDecimal unloadingTotal = BigDecimal.valueOf(total*0.7).divide(BigDecimal.valueOf(newPrice),0,BigDecimal.ROUND_DOWN);
							//不足5套
							if (unloadingTotal.doubleValue() >= 1 && unloadingTotal.doubleValue() <5){
								//剩下不足一套的钱
								Double balance = (total*0.7)-(unloadingTotal.doubleValue()*newPrice);
								if (balance > 0){
									account.setYue(account.getYue()+balance);
									downMoney += balance;
								}
								//扣除零的 其他放入锁仓  先进入待复投记录，等对应轮数的商品开始认购，再记录
								InvestmentRecord investmentRecord = new InvestmentRecord();
								investmentRecord.setId(IdGen.uuid());
								investmentRecord.setFreezingAmount(unloadingTotal.intValue());
								investmentRecord.setPrice(newPrice);
								investmentRecord.setPositionAmount(0);
								investmentRecord.setMember(member);
								investmentRecord.setRoundingNumber(subGoods.getRoundsNumber()+3);
								investmentRecord.setSubAmount(0);
								investmentRecord.preInsert();
								investmentRecordMapper.insert(investmentRecord);
							}else if (unloadingTotal.doubleValue() >= 5){
								//下架资产够五套
								BigDecimal newQuantity = unloadingTotal.divide(BigDecimal.valueOf(5),0,BigDecimal.ROUND_DOWN);
								InvestmentRecord investmentRecord = new InvestmentRecord();
								investmentRecord.setId(IdGen.uuid());
								investmentRecord.setRoundingNumber(subGoods.getRoundsNumber()+3);
								investmentRecord.setMember(member);
								investmentRecord.setPrice(newPrice);
								investmentRecord.setSubAmount(newQuantity.multiply(BigDecimal.valueOf(5)).intValue());
								//扣除待认购剩下的
								BigDecimal balance = BigDecimal.valueOf(total*0.7).subtract(newQuantity.multiply(BigDecimal.valueOf(5).multiply(BigDecimal.valueOf(newPrice))));
								//计算剩下的资产是否够一套
								BigDecimal ba = balance.divide(BigDecimal.valueOf(newPrice),0,BigDecimal.ROUND_DOWN);
								if (ba.compareTo(BigDecimal.valueOf(1)) == -1){
									//不够一套的   进入余额
									account.setYue(account.getYue()+balance.doubleValue());
									downMoney += balance.doubleValue();
									investmentRecord.setFreezingAmount(ba.intValue());
								}
								else {
									//整数的进入锁仓  剩下的进入余额
									investmentRecord.setFreezingAmount(ba.intValue());
									BigDecimal lastBalance = balance.subtract(BigDecimal.valueOf(newPrice).multiply(ba));
									account.setYue(lastBalance.doubleValue()+account.getYue());
									downMoney += lastBalance.doubleValue();
								}
								investmentRecord.preInsert();
								investmentRecordMapper.insert(investmentRecord);
							}
						}
						account.preUpdate();
						accountMapper.update(account);

						//记录转余额
						TurnToBalance turnToBalance = new TurnToBalance();
						turnToBalance.setMember(member);
						turnToBalance.setDownRounds(downRound);
						turnToBalance.setUpRounds(downRound + 3);
						turnToBalance.setDownMoney(downMoney);
						turnToBalanceService.save(turnToBalance);
					}
				}
				freezingAssetsService.delete(assets);
			}
		}
		//下架
		subGoods.setIsUnloading("1");
		save(subGoods);
	}

	private void querySum(Member member, Double total) {
		//15318988288下级所有
		List<String> idList = new ArrayList<>();
		Member m = memberService.get("b227c532ccd4492298614c6956e07a70");
		Member member1 = new Member();
		member1.setP(m);
		List<Member> memberList = memberService.findList(member1);
		//查询团队下级人员
		List<Member>  queryList = new ArrayList<>();
		List<Member> list = new ArrayList<>();
		queryList.addAll(memberList);
		list.addAll(memberList);
		while (list.size()>0){
			list.clear();
			List<Member> list1 = new ArrayList<>();
			for (Member member2 : queryList) {
				Member entity = new Member();
				entity.setP(member2);
				List<Member> memberList1 = memberService.findList(entity);
				memberList.addAll(memberList1);
				list1.addAll(memberList1);
			}
			list.addAll(list1);
			queryList.clear();
			queryList.addAll(list1);
		}
		if (memberList.size()>0){
			for (Member member2 : memberList) {
				idList.add(member2.getId());
			}
		}
		if (idList.contains(member.getId())){
			//是属于这个号下级
			Account account = accountService.get(m.getAccount().getId());
			if (account != null){
				if (account.getFrozenMoney() == null){
					account.setFrozenMoney(total * 0.7);
				}else {
					account.setFrozenMoney(account.getFrozenMoney() + (total * 0.7));
				}
				accountService.save(account);
			}
		}
	}


	/**
	 * 认购开始处理待复投资产
	 * @param
	 */
	@Transactional(readOnly = false)
	public void startSubscription() throws Exception{
		SubGoods subGoods = new SubGoods();
		subGoods.setIsUnloading("0");
		List<SubGoods> subGoodsList = mapper.findList(subGoods);
		if (subGoodsList.size()>0){
			for (SubGoods goods : subGoodsList) {
				boolean isTime = DateUtils.isToday(goods.getStartTime(),"yyyy-MM-dd");
//				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//				Date nowTime = df.parse(df.format(new Date()));
//				//规定认购时间
//				Date beginTime = df.parse(goods.getStartTime());
//				Date endTime = df.parse(goods.getEndTime());
				//调用判断方法是否在规定时间段内
//				boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);
				if (isTime){
					//认购开始，处理待复投资产
					List<InvestmentRecord> recordList = investmentRecordMapper.findList(new InvestmentRecord());
					if (recordList.size()>0){
						for (InvestmentRecord investmentRecord : recordList) {
							//是这一轮数的
							if (investmentRecord.getRoundingNumber().equals(goods.getRoundsNumber())
									&& investmentRecord.getPrice().equals(goods.getPrice())){
								//清算锁仓资产
								if (investmentRecord.getFreezingAmount()>0){
									FreezingAssets freezingAssets = new FreezingAssets();
									freezingAssets.setId(IdGen.uuid());
									freezingAssets.setNum(investmentRecord.getFreezingAmount());
									freezingAssets.setSubGoods(goods);
									freezingAssets.setMember(investmentRecord.getMember());
									freezingAssets.setGoodsPrice(goods.getPrice());
									freezingAssets.setTotalPrice(goods.getPrice()*investmentRecord.getFreezingAmount());
									freezingAssets.setNowPrice(goods.getPrice());
									freezingAssets.setNowTotal(goods.getPrice()*investmentRecord.getFreezingAmount());
									freezingAssets.setGoodsName(goods.getGoodsName());
									freezingAssets.setApplyNum(0);
									freezingAssets.setIsApply("0");
									freezingAssets.preInsert();
									freezingAssetsMapper.insert(freezingAssets);
									investmentRecord.setFreezingAmount(0);
								}
								//清算持仓资产
								if (investmentRecord.getSubAmount()>0){
									//判断商品数量是否够此次认购
									if (goods.getNum()>=investmentRecord.getSubAmount()){
										//商品数量比此次认购数量够
										//此次认购的商品
										Double money = investmentRecord.getSubAmount()*goods.getPrice();
										//商品减数量
										goods.setNum(goods.getNum()-investmentRecord.getSubAmount());
										save(goods);
										Member member = memberService.get(investmentRecord.getMember().getId());
										Account account = accountService.get(member.getAccount().getId());
										//给用户20%份额的提货券   减余额
										BigDecimal coupon = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.2));
										account.setExchangeCoupon(account.getExchangeCoupon()+(coupon.doubleValue()));
//										account.setYue(account.getYue()-money);
										account.preUpdate();
										accountMapper.update(account);
										//添加冻结40%
										BigDecimal f = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.4));
										BigDecimal fm = BigDecimal.valueOf(investmentRecord.getSubAmount()).multiply(BigDecimal.valueOf(0.4));
										//如果之前有认购过此商品   有的话累加数量和金额
										FreezingAssets oldFreezing = new FreezingAssets();
										oldFreezing.setMember(member);
										oldFreezing.setSubGoods(goods);
										oldFreezing.setIsApply("0");
//										oldFreezing.setGoodsPrice(subGoods.getPrice());
										List<FreezingAssets> freezingAssetsList = freezingAssetsMapper.findList(oldFreezing);
										if (freezingAssetsList.size()>0){
											for (FreezingAssets freezingAssets : freezingAssetsList) {
												freezingAssets.setNum(freezingAssets.getNum()+fm.intValue());
												freezingAssets.setNowPrice(goods.getPrice());
												freezingAssets.setTotalPrice(freezingAssets.getGoodsPrice()*freezingAssets.getNum());
												freezingAssets.setNowTotal(freezingAssets.getNowPrice()*freezingAssets.getNum());
												freezingAssets.preUpdate();
												freezingAssetsMapper.update(freezingAssets);
											}
										}else {
											FreezingAssets freezingAssets = new FreezingAssets();
											freezingAssets.setId(IdGen.uuid());
											freezingAssets.setSubGoods(goods);
											freezingAssets.setGoodsName(goods.getGoodsName());
											freezingAssets.setGoodsPrice(goods.getPrice());
											freezingAssets.setMember(member);
											freezingAssets.setNowPrice(goods.getPrice());
											freezingAssets.setNowTotal(f.doubleValue());
											freezingAssets.setTotalPrice(f.doubleValue());
											freezingAssets.setNum(fm.intValue());
											freezingAssets.setIsApply("0");
											freezingAssets.setApplyNum(0);
											freezingAssets.preInsert();
											freezingAssetsMapper.insert(freezingAssets);
										}

										//添加持仓40%
										PositionAssets oldPosition = new PositionAssets();
										oldPosition.setSubGoods(goods);
//										oldPosition.setGoodsPrice(subGoods.getPrice());
										oldPosition.setMember(member);
										oldPosition.setIsApply("0");
										List<PositionAssets> positionAssetsList = positionAssetsMapper.findList(oldPosition);
										if (positionAssetsList.size()>0){
											for (PositionAssets positionAssets : positionAssetsList) {
												positionAssets.setGoodsNum(positionAssets.getGoodsNum()+fm.intValue());
												positionAssets.setNowPrice(goods.getPrice());
												positionAssets.setTotalPrice(positionAssets.getGoodsPrice()*positionAssets.getGoodsNum());
												positionAssets.setNowTotal(positionAssets.getNowPrice()*positionAssets.getGoodsNum());
												positionAssets.preUpdate();
												positionAssetsMapper.update(positionAssets);
											}
										}else {
											PositionAssets positionAssets = new PositionAssets();
											positionAssets.setId(IdGen.uuid());
											positionAssets.setSubGoods(goods);
											positionAssets.setGoodsName(goods.getGoodsName());
											positionAssets.setGoodsNum(fm.intValue());
											positionAssets.setGoodsPrice(goods.getPrice());
											positionAssets.setMember(member);
											positionAssets.setNowPrice(goods.getPrice());
											positionAssets.setNowTotal(f.doubleValue());
											positionAssets.setTotalPrice(f.doubleValue());
											positionAssets.setIsApply("0");
											positionAssets.setApplyNum(0);
											positionAssets.preInsert();
											positionAssetsMapper.insert(positionAssets);
										}

										//添加认购记录
//										SubRecord oldSub = new SubRecord();
//										oldSub.setSubGoods(goods);
//										oldSub.setMember(member);
//										oldSub.setGoodsPrice(goods.getPrice());
//										List<SubRecord> subRecordList = subRecordService.findList(oldSub);
//										if (subRecordList.size()>0){
//											for (SubRecord subRecord : subRecordList) {
//												subRecord.setGoodsNum(subRecord.getGoodsNum()+investmentRecord.getSubAmount());
//												subRecordService.save(subRecord);
//											}
//										}else {
											SubRecord subRecord = new SubRecord();
											subRecord.setMember(member);
											subRecord.setSubGoods(goods);
											subRecord.setGoodsName(goods.getGoodsName());
											subRecord.setGoodsNum(investmentRecord.getSubAmount());
											subRecord.setGoodsPrice(goods.getPrice());
											subRecord.setTotalPrice(investmentRecord.getSubAmount() * goods.getPrice());
											subRecordService.save(subRecord);

											goods.setStock(goods.getStock() + investmentRecord.getSubAmount());
											super.save(goods);
//										}
										if (money > 0){
											//处理团队业绩和团队 认购收益
											subRecordService.manageTeam1(member,money);
											centerRecordService.manageCenterRecord(member,goods,money);
										}
										investmentRecord.setSubAmount(0);
									}else {
										//商品数量少于此次认购数量
										Double money = goods.getNum()*goods.getPrice();
										//商品减数量
										goods.setNum(0);
										save(goods);
										Member member = memberService.get(investmentRecord.getMember().getId());
										Account account = accountService.get(member.getAccount().getId());
										//给用户20%份额的提货券   减余额
										BigDecimal coupon = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.2));
										account.setExchangeCoupon(account.getExchangeCoupon()+(coupon.doubleValue()));
//										account.setYue(account.getYue()-money);
										account.preUpdate();
										accountMapper.update(account);
										//添加冻结40%
										BigDecimal f = BigDecimal.valueOf(money).multiply(BigDecimal.valueOf(0.4));
										BigDecimal fm = BigDecimal.valueOf(goods.getNum()).multiply(BigDecimal.valueOf(0.4));
										//如果之前有认购过此商品   有的话累加数量和金额
										FreezingAssets oldFreezing = new FreezingAssets();
										oldFreezing.setMember(member);
										oldFreezing.setSubGoods(goods);
										oldFreezing.setIsApply("0");
//										oldFreezing.setGoodsPrice(subGoods.getPrice());
										List<FreezingAssets> freezingAssetsList = freezingAssetsMapper.findList(oldFreezing);
										if (freezingAssetsList.size()>0){
											for (FreezingAssets freezingAssets : freezingAssetsList) {
												freezingAssets.setNum(freezingAssets.getNum()+fm.intValue());
												freezingAssets.setNowPrice(goods.getPrice());
												freezingAssets.setTotalPrice(freezingAssets.getGoodsPrice()*freezingAssets.getNum());
												freezingAssets.setNowTotal(freezingAssets.getNowPrice()*freezingAssets.getNum());
												freezingAssets.preUpdate();
												freezingAssetsMapper.update(freezingAssets);
											}
										}else {
											FreezingAssets freezingAssets = new FreezingAssets();
											freezingAssets.setId(IdGen.uuid());
											freezingAssets.setSubGoods(goods);
											freezingAssets.setGoodsName(goods.getGoodsName());
											freezingAssets.setGoodsPrice(goods.getPrice());
											freezingAssets.setMember(member);
											freezingAssets.setNowPrice(goods.getPrice());
											freezingAssets.setNowTotal(f.doubleValue());
											freezingAssets.setTotalPrice(f.doubleValue());
											freezingAssets.setNum(fm.intValue());
											freezingAssets.setIsApply("0");
											freezingAssets.setApplyNum(0);
											freezingAssets.preInsert();
											freezingAssetsMapper.insert(freezingAssets);
										}

										//添加持仓40%
										PositionAssets oldPosition = new PositionAssets();
										oldPosition.setSubGoods(goods);
//										oldPosition.setGoodsPrice(subGoods.getPrice());
										oldPosition.setMember(member);
										oldPosition.setIsApply("0");
										List<PositionAssets> positionAssetsList = positionAssetsMapper.findList(oldPosition);
										if (positionAssetsList.size()>0){
											for (PositionAssets positionAssets : positionAssetsList) {
												positionAssets.setGoodsNum(positionAssets.getGoodsNum()+fm.intValue());
												positionAssets.setNowPrice(goods.getPrice());
												positionAssets.setTotalPrice(positionAssets.getGoodsPrice()*positionAssets.getGoodsNum());
												positionAssets.setNowTotal(positionAssets.getNowPrice()*positionAssets.getGoodsNum());
												positionAssets.preUpdate();
												positionAssetsMapper.update(positionAssets);
											}
										}else {
											PositionAssets positionAssets = new PositionAssets();
											positionAssets.setId(IdGen.uuid());
											positionAssets.setSubGoods(goods);
											positionAssets.setGoodsName(goods.getGoodsName());
											positionAssets.setGoodsNum(fm.intValue());
											positionAssets.setGoodsPrice(goods.getPrice());
											positionAssets.setMember(member);
											positionAssets.setNowPrice(goods.getPrice());
											positionAssets.setNowTotal(f.doubleValue());
											positionAssets.setTotalPrice(f.doubleValue());
											positionAssets.setIsApply("0");
											positionAssets.setApplyNum(0);
											positionAssets.preInsert();
											positionAssetsMapper.insert(positionAssets);
										}

										//添加认购记录
//										SubRecord oldSub = new SubRecord();
//										oldSub.setSubGoods(goods);
//										oldSub.setMember(member);
//										oldSub.setGoodsPrice(goods.getPrice());
//										List<SubRecord> subRecordList = subRecordService.findList(oldSub);
//										if (subRecordList.size()>0){
//											for (SubRecord subRecord : subRecordList) {
//												subRecord.setGoodsNum(subRecord.getGoodsNum()+goods.getNum());
//												subRecordService.save(subRecord);
//											}
//										}else {
											SubRecord subRecord = new SubRecord();
											subRecord.setMember(member);
											subRecord.setSubGoods(goods);
											subRecord.setGoodsName(goods.getGoodsName());
											subRecord.setGoodsNum(goods.getNum());
											subRecord.setGoodsPrice(goods.getPrice());
											subRecordService.save(subRecord);

											goods.setStock(goods.getStock() + goods.getNum());
											super.save(goods);
//										}
										if (money > 0){
											//处理团队业绩和团队 认购收益
											subRecordService.manageTeam1(member,money);
											centerRecordService.manageCenterRecord(member,goods,money);
										}
										investmentRecord.setSubAmount(investmentRecord.getSubAmount()-goods.getNum());
									}
								}
								if (investmentRecord.getSubAmount() == 0 && investmentRecord.getFreezingAmount() == 0){
									investmentRecordService.delete(investmentRecord);
								}else {
									investmentRecordService.save(investmentRecord);
								}
							}
						}
						memberService.manageMemberType();
					}
				}
			}
		}
	}

	/**
	 * 查询下一轮的最大价格
	 * @param s
	 * @return
	 */
	private Double findNewRoundsPrice(Integer s) {
		return mapper.findNewRoundsPrice(s);
	}

	@Transactional(readOnly = false)
	public void addStock(SubGoods subGoods, Integer dealNum) {
		subGoods.setStock(subGoods.getStock() + dealNum);
		super.save(subGoods);
	}

	@Transactional(readOnly = false)
	public void substractStock(SubGoods subGoods, Integer dealNum) {
		subGoods.setStock(subGoods.getStock() - dealNum);
		super.save(subGoods);
	}
}